package com.omesoft.hksnore.report;


import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.omesoft.hksnore.R;
import com.omesoft.hksnore.monitoring.CalendarSelectFragment;
import com.omesoft.hksnore.monitoring.MonitorCalendarSelectActivity;
import com.omesoft.hksnore.monitoring.MonitorFragment;
import com.omesoft.hksnore.util.L;
import com.omesoft.hksnore.util.MySleepHandler;
import com.omesoft.hksnore.util.constant.CusConstant;
import com.omesoft.hksnore.util.dao.MendaleSleepAllIfcImpl;
import com.omesoft.hksnore.util.dao.MendaleSleepIfcImpl;
import com.omesoft.hksnore.util.data.MyDateUtil;
import com.omesoft.hksnore.util.data.MySharedPreferencesUtil;
import com.omesoft.hksnore.util.data.SortComparator;
import com.omesoft.hksnore.util.dialog.MyProgressBarDialogUtil;
import com.omesoft.hksnore.util.entity.Medix_Pub_Sync_Sleep;
import com.omesoft.hksnore.util.entity.Medix_Pub_Sync_SleepDetail;
import com.omesoft.hksnore.util.entity.TempDate;
import com.omesoft.hksnore.util.json.HypnotistWSUtil;
import com.omesoft.hksnore.util.json.ReErrorCode;
import com.omesoft.hksnore.util.json.SyncUtil;
import com.omesoft.hksnore.util.myactivity.BaseFragment;
import com.omesoft.hksnore.util.omeview.ColorArcProgressBar;
import com.omesoft.hksnore.util.omeview.MyDialog;
import com.omesoft.hksnore.util.photo.SettingUtil;
import com.omesoft.hksnore.util.titlebar.MyTitlebarUtil;
import com.omesoft.hksnore.util.web.CheckNetwork;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * 报告界面
 *
 * @autor omesoft_lgc
 * <p/>
 * create at 2017/2/16 15:29
 */
public class ReportFragment extends BaseFragment implements OnClickListener {
    private String TAG = "ReportFragment";

    private View mainView;
    private Context context;
    private Activity activity;
    private RelativeLayout mReplay_rl, mCalendar_rl;
    private TextView mData_text;
    private TextView mSnoreCount_tv, mSnoreTimeHour_tv, mSnoreTImeMin_tv, mSnoreStopCount_tv,
            mBreathing_tv, mMove_tv, mTurnMova_tv, mNoData_tv, mSnoreTimeMorS_tv;
    private final int HANDLER_BATTERY = 7;
    private final int HANDLER_UPDATE = 1;
    private final int HANDLER_REFRESH = 2;// 刷新控件
    private final int HANDLER_RELOAD_SLEEP_ID = 233;
    private final int HANDLER_RELOAD_SLEEP = 2333;
    private ImageView mReplay_img, mDelect_img;
    private ImageButton mDataPre_ib, mDataNext_id;

    private MendaleSleepAllIfcImpl allIfc;
    private MendaleSleepIfcImpl mifc;


    private String SleepID;
    private File SleepFile;
    private List<Medix_Pub_Sync_Sleep> dtos;
    private List<Medix_Pub_Sync_Sleep> selectDateDto;
    private Medix_Pub_Sync_Sleep selectDto;
    private List<Medix_Pub_Sync_SleepDetail> dtosDetail;
    private Medix_Pub_Sync_Sleep dto;

    private ColorArcProgressBar colorArcProgressBar;


    private List<TempDate> dataBeans;// 记录睡眠id和时间，用于上一个、下一个
    private boolean isFrist = true;


    private int position = 0;// 当前记录在表中的位置
    private int totalSize = 0;// 所有记录总数'
    private String startTime, endTime = "";

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.activity = activity;
        context = getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mainView = inflater.inflate(R.layout.snore_fragment_report, container, false);
        return mainView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        init();
        initHandler();
        initView();
        initTitle();
        loadDate("", 0);
        loadSleepData(1, 0);
    }


    @Override
    protected void init() {
        Log.e(TAG, "init: ");
        allIfc = new MendaleSleepAllIfcImpl(context);
        mifc = new MendaleSleepIfcImpl(context);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }


    private void initTitle() {
        MyTitlebarUtil.setStateHeight(getActivity(), mainView.findViewById(R.id.state_bar), R.string.snore_main_report, mainView);

        if (CheckNetwork.checkNetwork(context)) {
            //每次打开都同步
            MySharedPreferencesUtil.setLocalTime(context, "1980-01-01 00:00:00");
            MySharedPreferencesUtil.setBodyTime(context, "0");
            SyncUtil.SyncSleepThread(context, handler);
            //只有重新登陆的时候才同步，备用方案
//            if (MySharedPreferencesUtil.getBodyTime(context).equals("0")) {
//                SyncUtil.SyncSleepThread(context, handler);//初次登陆时，服务器返回的时间戳默认为0，这时候就开启数据同步
//            }
        }
    }

    protected void initView() {
        mReplay_rl = (RelativeLayout) mainView.findViewById(R.id.report_rl_replay);
        mReplay_rl.setOnClickListener(this);
        mDataPre_ib = (ImageButton) mainView.findViewById(R.id.report_pre_ib_);
        mDataPre_ib.setOnClickListener(this);
        mDataNext_id = (ImageButton) mainView.findViewById(R.id.report_next_ib_);
        mDataNext_id.setOnClickListener(this);
        mCalendar_rl = (RelativeLayout) mainView.findViewById(R.id.report_calendar);
        mCalendar_rl.setOnClickListener(this);
        mReplay_img = (ImageView) mainView.findViewById(R.id.report_play_img);
        colorArcProgressBar = (ColorArcProgressBar) mainView.findViewById(R.id.main_weight_ProgressBar);
        mDelect_img = (ImageView) mainView.findViewById(R.id.report_delect);
        mDelect_img.setOnClickListener(this);

        mNoData_tv = (TextView) mainView.findViewById(R.id.report_no_data);
        mSnoreTimeMorS_tv = (TextView) mainView.findViewById(R.id.report_sonre_m_or_s);
        mData_text = (TextView) mainView.findViewById(R.id.report_data_text);
        mSnoreTimeHour_tv = (TextView) mainView.findViewById(R.id.report_sonre_time_hour);
        mSnoreTImeMin_tv = (TextView) mainView.findViewById(R.id.report_sonre_time_min);
        mSnoreCount_tv = (TextView) mainView.findViewById(R.id.report_sonre_count);
        mSnoreStopCount_tv = (TextView) mainView.findViewById(R.id.report_sonre_stop);
        mBreathing_tv = (TextView) mainView.findViewById(R.id.report_sonre_breath);
        mMove_tv = (TextView) mainView.findViewById(R.id.report_sonre_time_move);
        mTurnMova_tv = (TextView) mainView.findViewById(R.id.report_sonre_turn_mova);

        colorArcProgressBar.setMaxValues(100);
        colorArcProgressBar.setCurrentValues(0,0);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
//            if (isFrist) {//判断是否第一次进入，如果是则不执行下面方法，以免重复获取浪费资源
//                isFrist = false;
//                return;
//            }

            //每次显示报告界面都查看数据库中今天的数据总量，如果有新的数据插入，则加载最新一条
//            String today = MyDateUtil.formateDate2(new Date());
//            int t = allIfc.findTotal(MySharedPreferencesUtil.getMemberId(context));
//            if (t > MySharedPreferencesUtil.getListSize(context)) {
//                mData_text.setText(today);
//                mData_text.setTag(today);
//                loadSleepData(1, 0);
//            }
            if (MonitorFragment.isMonitorEnd == true) {
                Log.e("show","11111");
                sendMsg(HANDLER_RELOAD_SLEEP);


            }


        }
    }

    protected void initHandler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case HANDLER_UPDATE:
                        loadView();
                        break;
                    case HANDLER_REFRESH:
                        int select = (int) msg.obj;
                        loadSleepData(0, select);
                        break;
                    case HANDLER_RELOAD_SLEEP:

                        ArrayList<Medix_Pub_Sync_Sleep> dtos = allIfc.findSleepIDAndStartDate(MySharedPreferencesUtil.getMemberId(context));
                        mData_text.setText(dtos.get(dtos.size() - 1).getStartDate().substring(0, 10));
                        mData_text.setTag(dtos.get(dtos.size() - 1).getStartDate().substring(0, 10));
                        loadSleepData(1, 0);
//                        reloadBySleepID();
                        break;
                    case ReErrorCode.SYNC_SUCCEDFUL:
                        loadDate("", 0);
                        loadSleepData(1, 0);
                        break;
                }
            }
        };
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.report_rl_replay:
                if (SleepFile.exists()) {

                    Intent intent = new Intent(context, RePlayActivity.class);
                    intent.putExtra("SleepID", SleepID);
                    intent.putExtra("SnoreCount", mSnoreCount_tv.getText().toString());
                    intent.putExtra("SnoreSropCount", mSnoreStopCount_tv.getText().toString());
                    intent.putExtra("SnoreTimeHour", mSnoreTimeHour_tv.getText().toString());
                    intent.putExtra("SnoreTimeMin", mSnoreTImeMin_tv.getText().toString());
                    intent.putExtra("BreathingRata", mBreathing_tv.getText().toString());
                    intent.putExtra("ActCount", mMove_tv.getText().toString());
                    intent.putExtra("TurnCount", mTurnMova_tv.getText().toString());
                    intent.putExtra("SnoreTimeMorS",mSnoreTimeMorS_tv.getText().toString());
                    intent.putExtra("startTime", startTime);
                    intent.putExtra("endTime", endTime);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.in_righttoleft, R.anim.out_righttoleft);

//                    jumpActivityNotFinish(activity, RePlayActivity.class, SleepID);
                }
                break;
            case R.id.report_calendar:
                startCalendarSelect();
                break;
            case R.id.report_next_ib_:

                sendMsg(HANDLER_REFRESH, 1);
                break;
            case R.id.report_pre_ib_:
                sendMsg(HANDLER_REFRESH, -1);
                break;
            case R.id.report_delect:
                showDelectDialog();
                break;
        }
        MySleepHandler.newInstance(context).setMonitorHandler(handler);


    }

    private void loadDate(String selectDate, int type) {
        String today = MyDateUtil.formateDate2(new Date());//获取今天的日期
        if (allIfc.findTotal(MySharedPreferencesUtil.getMemberId(context)) > 0) {
            dataBeans = new LinkedList<TempDate>();
            ArrayList<Medix_Pub_Sync_Sleep> dtos = allIfc.findSleepIDAndStartDate(MySharedPreferencesUtil.getMemberId(context));
            int size = dtos.size();


            for (int i = 0; i < size; i++) {
                Medix_Pub_Sync_Sleep dto = dtos.get(i);
                /**
                 * 加载睡眠情况
                 * */
                int tempSize = mifc.findTotal(dto.getSleepID(), MySharedPreferencesUtil.getMemberId(context));

                if (tempSize == 0) {
                    HypnotistWSUtil.GetSleepDetailBySleepId(context, handler, dto.getSleepID());
                }

                String str = dto.getStartDate().substring(0, 10);
                String[] date = str.split("-");
                TempDate bean = new TempDate();
                bean.setDate(date[0] + "-" + date[1] + "-" + date[2]);
                dataBeans.add(bean);
                L.e("loadDate: " + str + "     " + date[0] + "-" + date[1] + "-" + date[2]);

            }

            /**
             * 显示有数据的最后一天
             * */
            mData_text.setText(dtos.get(size - 1).getStartDate().substring(0, 10));
            mData_text.setTag(dtos.get(size - 1).getStartDate().substring(0, 10));

            /**
             * 去重复，排序
             * */
            getNewList(dataBeans, selectDate);
            totalSize = dataBeans.size();
//            Log.e(TAG, "loadDate: " + totalSize);

        } else {
            totalSize = 0;
            position = 0;
            mData_text.setText(today);
            mData_text.setTag(today);
        }

        loadTodaySleepData2();
    }

    /**
     * 去掉数据重复
     *
     * @param li 数据集合
     * @return
     */

    public void getNewList(List<TempDate> li, String selectDate) {
        /**
         * 过滤掉重复日期
         * */
        for (int i = 0; i < li.size(); i++) {
            for (int j = li.size() - 1; j < i; j--) {
                if (li.get(j).getDate().equals(li.get(i).getDate())) {
                    li.remove(j);
                }
            }

        }
        /**
         * 排序
         * */
        Log.e(TAG, "排序: ");
        Comparator<TempDate> comp = new SortComparator();
        Collections.sort(li, comp);
        int size = li.size();
        /**
         * 拿时间位置
         * */
        for (int i = 0; i < size; i++) {
//            Log.e(TAG, selectDate + "  " + i + " 时间   " + li.get(i).getDate());
            if (selectDate.equals(li.get(i).getDate())) {
//                Log.e(TAG, "位置  " + i);
                position = i;


                mData_text.setText(li.get(i).getDate());
                mData_text.setTag(li.get(i).getDate());
                break;
            }
        }
        /**
         * 预防找不到时间位置
         * */
        if (mData_text.getTag().toString().equals(null) || mData_text.getTag().toString() == null) {
            Log.e(TAG, "找不到时间位置 ");


            mData_text.setText(li.get(size - 1).getDate());
            mData_text.setText(li.get(size - 1).getDate());
            position = size - 1;

        }
        dataBeans = li;
    }

    private void startCalendarSelect() {
        // text_date.setText("2016-05-02");


        CalendarSelectFragment.selectDate = mData_text.getTag().toString().trim();
        Log.e(TAG, "startCalendarSelect: " + CalendarSelectFragment.selectDate);
        Intent intent = new Intent(context, MonitorCalendarSelectActivity.class);
        String str = mData_text.getTag().toString().trim().substring(0, 7);
        intent.putExtra("month", str);
        startActivityForResult(intent, 1);
        getActivity().overridePendingTransition(R.anim.monitor_calendarselect_enter, R.anim.monitor_calendarselect_exit);
        // overridePendingTransition(0 , 0);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1:
                if (resultCode == Activity.RESULT_OK) {
                    String date = data.getStringExtra("CalendarResult");
                    Log.i(TAG, "onActivityResult: " + date);
                    loadDataByDate(date);
                    break;

                }
        }
    }

    private Dialog confirmDialog;

    private void showDelectDialog() {
        final MyDialog.Builder builder = new MyDialog.Builder(getActivity());
        builder.setTitle(R.string.repotr_delect);
        builder.setPositiveButton(getString(R.string.snore_main_btn_sure),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        delectSleepInfo();
                        confirmDialog.dismiss();

                    }
                });
        builder.setNegativeButton(getString(R.string.snore_main_btn_cancel),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        confirmDialog.dismiss();
                    }
                });
        confirmDialog = builder.create();
        confirmDialog.show();
    }

    /**
     * 选择日期之后的加载
     */
    private void loadDataByDate(String date) {

        mData_text.setText(date);
        mData_text.setTag(date);
        loadDate(date, 1);
        loadSleepData(1, 0);
        loadTodaySleepData2();

    }


    /**
     * @param type   为1时加载选中日期的数据，为0时切换当天的数据
     * @param select 上一个或下一个的位置
     */
    private void loadSleepData(int type, int select) {
        CusConstant.nowSleepTotalTime = 0f;
        CusConstant.resultSleepTotalTime = 0f;

        int last = 0;
        if (type == 1) {
            selectDateDto = allIfc.findByDateAndMemberId(mData_text.getTag().toString(), MySharedPreferencesUtil.getMemberId(context));
        }
        dtos = allIfc.findSleepByMemberId(MySharedPreferencesUtil.getMemberId(context));
        totalSize = dtos.size();
        last = dtos.size() - 1;

        Log.e("hehe","loadSleepData   totalSize="+totalSize);

        if (totalSize > 0) {
            mReplay_rl.setEnabled(true);
            mNoData_tv.setText(R.string.repotr_replay_data);
            mReplay_img.setImageResource(R.mipmap.report_playback);
            if (type == 1) {
                if (selectDateDto.size() > 0) {
                    selectDto = selectDateDto.get(selectDateDto.size() - 1);//选择日期时默认加载当天最后一条记
                    for (int i = totalSize - 1; i >= 0; i--) {
                        if (selectDto.getSleepID().equals(dtos.get(i).getSleepID())) {
                            position = i;
                            break;
                        }

                    }
                }

            } else {
                int currentPostion = this.position + select;
                if (currentPostion >= 0 && currentPostion <= last) {
                    dto = dtos.get(currentPostion);//切换上一条或下一条记录
                    this.position = currentPostion;
                }
            }

            if (type == 1) {
                if (selectDto != null) {
                    setSleepValue(selectDto);
                }

            } else {
                if (dto != null) {

                    setSleepValue(dto);
                }
            }

            mDelect_img.setVisibility(View.VISIBLE);
        } else {
            mDelect_img.setVisibility(View.GONE);

        }
        loadTodaySleepData2();


    }


    /**
     * 显示睡眠信息
     */
    private void setSleepValue(Medix_Pub_Sync_Sleep dto) {
        if (dto != null)
            mSnoreCount_tv.setText(dto.getSnoreCount() + "");//打鼾次数
        mSnoreStopCount_tv.setText(dto.getSnoreStopCount() + "");//止鼾次数
        mBreathing_tv.setText(dto.getBreathRate() + "");//呼吸频率
        mMove_tv.setText(dto.getActCount() + "");//体动
        mTurnMova_tv.setText(dto.getTurnCount() + "");//翻身
        setSnoreTime(dto.getSnoreTime());//打鼾时长
        SleepID = dto.getSleepID();
        setReplayDataState(SleepID);
        String date = dto.getStartDate().substring(0, 10);
        dtosDetail = mifc.findAllSleepDetaiBySleepId(SleepID);
        mData_text.setText(date);
        mData_text.setTag(date);
        startTime = dto.getStartDate();
        endTime = dto.getEndDate();
        setViewValue(dtosDetail, startTime, endTime);
        if (MonitorFragment.isMonitorEnd) {
            MonitorFragment.isMonitorEnd = false;
            Log.e("show","44444");
            MyProgressBarDialogUtil.dismiss2Msg(R.string.snore_main_save_result_succes);
        }

    }

    /**
     * @param startTime 监测开始时间
     * @param endTime   监测结束时间，用于减去开始时间得出总时长
     * @param list      鼾声记录列表
     */

    private void setViewValue(List<Medix_Pub_Sync_SleepDetail> list, String startTime, String endTime) {
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            Date start = df.parse(startTime);
            Date end = df.parse(endTime);
            MySharedPreferencesUtil.setTempSleepID(context, SleepID);
            MySharedPreferencesUtil.setTempEndTime(context, endTime);
            MySharedPreferencesUtil.setTempStartTime(context, startTime);

            float maxValue = (end.getTime() - start.getTime()) / 60 / 1000;//获取时间差分钟数
            colorArcProgressBar.setMaxValues(maxValue);
            colorArcProgressBar.setSnoreList(list, MyDateUtil.stringTOlongDate(startTime), MyDateUtil.stringTOlongDate(endTime));//发送载有鼾声数据的实例以及记录的开始时间用于计算自定义view的图像
            String sh = "";
            String sm = "";
            String eh = "";
            String em = "";
            if (start.getHours() < 10) {
                sh = "0" + start.getHours();
            } else {
                sh = start.getHours() + "";
            }
            if (start.getMinutes() < 10) {
                sm = "0" + start.getMinutes();
            } else {
                sm = start.getMinutes() + "";
            }
            if (end.getHours() < 10) {
                eh = "0" + end.getHours();
            } else {
                eh = end.getHours() + "";
            }
            if (end.getMinutes() < 10) {
                em = "0" + end.getMinutes();
            } else {
                em = end.getMinutes() + "";
            }

            colorArcProgressBar.setTime(sh + ":" + sm, eh + ":" + em);
            colorArcProgressBar.startCustomAnimation();


        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    protected void sendMsg(int whatId) {
        Message msg = Message.obtain();
        msg.what = whatId;
        Log.v("sendMsg", "msg.what=" + msg.what);
        if (handler != null) {
            handler.sendMessage(msg);
        }
    }

    /**
     * 打鼾时长计算
     */
    private void setSnoreTime(int s) {
        int time = Math.round(s / 60);
        int hour = time / 60;
        int min = Math.round(time % 60);

        if (s < 60) {
            mSnoreTimeHour_tv.setText("00");
            if (s < 10) {
                mSnoreTImeMin_tv.setText("0" + s);
            } else {
                mSnoreTImeMin_tv.setText(s + "");
            }
            mSnoreTimeMorS_tv.setText(R.string.snore_his_second);
            return;
        }
        if (time >= 0) {
            mSnoreTimeMorS_tv.setText(R.string.snore_his_minute);
            if (time < 60) {
                mSnoreTimeHour_tv.setText("00");
                if (time < 10) {
                    mSnoreTImeMin_tv.setText("0" + time);

                } else {
                    mSnoreTImeMin_tv.setText("" + time);

                }
            } else {
                if (hour < 10) {
                    mSnoreTimeHour_tv.setText("0" + hour);
                    if (min >= 0 && min < 10) {
                        mSnoreTImeMin_tv.setText("0" + min);

                    } else {
                        mSnoreTImeMin_tv.setText(min + "");

                    }
                } else {
                    mSnoreTimeHour_tv.setText(hour + "");
                    if (min >= 0 && min < 10) {
                        mSnoreTImeMin_tv.setText("0" + min);

                    } else {
                        mSnoreTImeMin_tv.setText(min + "");

                    }
                }
            }
        }
    }

    private void setReplayDataState(String id) {
        SleepFile = new File(SettingUtil.TEXT_DIR + "/" + id + ".txt");
        if (!SleepFile.exists()) {
            mNoData_tv.setText(R.string.repotr_replay_no_data);
            mReplay_img.setImageResource(R.mipmap.report_playback_no);
            mReplay_rl.setEnabled(false);
        } else {
            mReplay_img.setImageResource(R.mipmap.report_playback);
            mNoData_tv.setText(R.string.repotr_replay_data);
            mNoData_tv.setEnabled(true);
            if (SleepFile.length() < 1000) {
                mNoData_tv.setText(R.string.repotr_replay_no_record_permission);
                mReplay_img.setImageResource(R.mipmap.report_playback_no);
                mReplay_rl.setEnabled(false);
            }
        }

    }

    /**
     * 加载日期选择控件的显示
     */
    private void loadTodaySleepData2() {

        if (totalSize > 1) {
            if (position == 0) {
                mDataPre_ib.setImageResource(R.mipmap.report_last_disabled);
                mDataPre_ib.setClickable(false);
                mDataNext_id.setImageResource(R.drawable.fragment_report_next_btn);
                mDataNext_id.setClickable(true);
            } else if (position == totalSize - 1) {
                mDataPre_ib.setImageResource(R.drawable.fragment_report_last_btn);
                mDataPre_ib.setClickable(true);
                mDataNext_id.setImageResource(R.mipmap.report_next_disabled);
                mDataNext_id.setClickable(false);

            } else {
                mDataPre_ib.setImageResource(R.drawable.fragment_report_last_btn);
                mDataPre_ib.setClickable(true);
                mDataNext_id.setImageResource(R.drawable.fragment_report_next_btn);
                mDataNext_id.setClickable(true);
            }
        } else if (totalSize == 0) {
            mDataPre_ib.setImageResource(R.mipmap.report_last_disabled);
            mDataNext_id.setImageResource(R.mipmap.report_next_disabled);
            mDataPre_ib.setClickable(false);
            mDataNext_id.setClickable(false);

            Time time = new Time();
            time.setToNow();
            mData_text.setText(time.format("%Y-%m-%d"));
            mData_text.setTag(time.format("%Y-%m-%d"));
            cleanData();
        } else if (totalSize == 1) {
            mDataPre_ib.setImageResource(R.mipmap.report_last_disabled);
            mDataNext_id.setImageResource(R.mipmap.report_next_disabled);
            mDataPre_ib.setClickable(false);
            mDataNext_id.setClickable(false);
        }

    }


    /***
     *
     * 删除操作
     */
    private void delectSleepInfo() {
        if (SleepFile.exists()) {
            SleepFile.delete();
        }
        if (totalSize != 0) {
            if (position == totalSize - 1) {
                position = position - 1;
            }
        }
        MySharedPreferencesUtil.setLocalTime(context, MyDateUtil.getDateFormatToString(null));
        allIfc.deleteByID(SleepID, MySharedPreferencesUtil.getMemberId(context), MySharedPreferencesUtil.getLocalTime(context));
        SyncUtil.SyncSleepThread(context, handler);
        Log.e(TAG, "delectSleepInfo: "+"totalSize="+totalSize+"    position="+position);
        loadSleepData(0, 0);

    }

    /**
     * 数据被删除为空时，请除界面显示的数据
     */
    private void cleanData() {
        mMove_tv.setText(R.string.monitor_1);
        mTurnMova_tv.setText(R.string.monitor_1);
        mSnoreCount_tv.setText(R.string.monitor_2);
        mSnoreStopCount_tv.setText(R.string.monitor_1);
        mSnoreTimeHour_tv.setText(R.string.monitor_2);
        mSnoreTImeMin_tv.setText(R.string.monitor_2);
        mBreathing_tv.setText(R.string.monitor_2);
        mDelect_img.setVisibility(View.GONE);
        mReplay_rl.setEnabled(false);
        mNoData_tv.setText(R.string.monitor_no_data);
        mReplay_img.setImageResource(R.mipmap.report_nodata);
        colorArcProgressBar.setTime("", "");
        if (dtosDetail != null) {
            dtosDetail.clear();
        }
        colorArcProgressBar.setSnoreList(dtosDetail, 0, 0);//发送载有鼾声数据的实例以及记录的开始时间用于计算自定义view的图像

    }

    /***
     * 刷新当前显示id的数据
     *
     */
    private void reloadBySleepID() {
        if (SleepID != null && !SleepID.equals("")) {
            Medix_Pub_Sync_Sleep temp = allIfc.findByID(SleepID, MySharedPreferencesUtil.getMemberId(context));
            setSleepValue(temp);
        }
    }

    @Override
    public void onDestroyView() {
        // TODO Auto-generated method stub
        super.onDestroyView();
    }
}

